package com.excilys.capicsoubank.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.excilys.capicsoubank.constraints.AmountIsValid;
import com.excilys.capicsoubank.form.TransferForm;

/**
 * Validator pour l'annotation CheckAmount.
 * 
 * @author "Grégory Coutant"
 * 
 */
public class AmountIsValidValidator implements
		ConstraintValidator<AmountIsValid, String> {

	private final Pattern p = Pattern
			.compile("^[0-9]{1,16}([,\\.][0-9]{1,2})?$");

	@Override
	public void initialize(AmountIsValid constraintAnnotation) {

	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {

		if (value == null || value.trim().isEmpty())
			return true;

		Matcher m = p.matcher(value);

		if (m.find() && TransferForm.getLongAmount(value) > 0)
			return true;

		return false;
	}
}
